「 自然語法 主張使用者定義的類型應當如同 一等公民一般。透過實作 運算子重載,我們允許類別使用標準符號(例如 + 或 ==),這能降低認知負荷,並符合 最小驚訝原則。
1. 結構與分派
運算子是一種具有特殊名稱的函數:關鍵字 operator 後接一個符號。一個 一元運算子 只有一個操作數,而一個 二元運算子 則有兩個操作數。當以 成員函數定義時,左側操作數會綁定至 隱含的 this 指標 (a.operator+(b))。若為 非成員,則兩者皆為明確的(operator+(a, b))。
2. 限制與倫理
C++ 防止「語言惡意破壞」:你無法創造新的符號(例如 **)或重新定義內建類型的操作(例如 int + int)。優先順序與結合性都是 不可變動的。架構原則:定義了 == 的類別可以輕鬆整合至如 std::find。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
Which of the following is an architecture principle mentioned in the text regarding operator overloading?
All functions should be renamed to operators to save space.
Classes defining
== make it easier to use library algorithms like std::find.Operator overloading should only be used for math classes.
Non-member operators are always preferred over member functions.
✅ Correct!
Correct. Providing expected operators like == allows standard library algorithms to interact with your types naturally.❌ Incorrect
Review the principle of integration with library algorithms like std::find.QUESTION 2
What happens if you try to define
int operator+(int, int)?The compiler issues a warning but allows it.
It successfully overrides the built-in addition.
It results in a compilation error.
It works only if the namespace is specified.
✅ Correct!
Correct. C++ forbids redefining operators for built-in types to maintain language stability.❌ Incorrect
C++ strictly prevents redefining built-in operations for fundamental types like int.QUESTION 3
In a member function version of a binary operator, how is the left-hand operand handled?
It is passed as the first explicit argument.
It is bound to the implicit
this pointer.It is ignored by the compiler.
It must be a static member.
✅ Correct!
Exactly. For a + b, if + is a member, a is the object on which the function is called.❌ Incorrect
Recall the difference between member functions (implicit this) and non-member functions (explicit parameters).QUESTION 4
Which of these operators CANNOT be overloaded?
new+=?:[]✅ Correct!
Correct. The conditional (ternary) operator is one of the few restricted from overloading.❌ Incorrect
Check Table 14.1; the dot, scope, and conditional operators are restricted.QUESTION 5
True or False: You can create a new operator
** for exponentiation in C++.True
False
✅ Correct!
Correct. You can only overload existing C++ operators; creating new symbols is not permitted.❌ Incorrect
C++ allows overloading existing symbols but not inventing new ones.Natural Syntax & Logic Implementation Case Study
Deep dive into operator mechanics and polymorphic behavior.
You are refining a library that handles mathematical types and polymorphic queries. You must ensure type safety and handle conversion ambiguities while implementing standard C++ patterns.
Q
Exercise 14.37: Write a class that tests whether two values are equal. Use that object and the library algorithms to write a program to replace all instances of a given value in a sequence.
Solution:
Implementation:
Implementation:
class EqualTest {
public:
EqualTest(int v) : val(v) {}
bool operator()(int x) const { return x == val; }
private:
int val;
};
Usage: std::replace_if(vec.begin(), vec.end(), EqualTest(old_val), new_val);. This uses the function call operator to create a predicate for the algorithm.Q
Exercise 14.50: Show the possible conversion sequences for 'int ex1 = ldobj;' and 'float ex2 = ldobj;' where LongDouble has conversions to both double and float.
Solution:
For
For
ex1 (int initialization): The initialization is ambiguous. The compiler can convert LongDouble to double OR float, and both then require a standard conversion to int. Neither path is better. For ex2 (float initialization): This is legal because the conversion operator to float is an exact match for the target type.Q
Exercise 15.1: What is a virtual member? [Word Count Requirement: 15 words]
Solution:
A base class function enabling dynamic binding by allowing derived classes to provide specific implementations.
A base class function enabling dynamic binding by allowing derived classes to provide specific implementations.